<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #333;
            color: #fff;
            text-align: center;
            padding: 1em;
        }

        section {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        h2 {
            color: #333;
        }

        form {
            margin-top: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
        }

        input {
            width: 100%;
            padding: 8px;
            margin-bottom: 16px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            background-color: #333;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #555;
        }

        #medical-record {
            display: none;
            /* 默认隐藏病历信息 */
            margin-top: 20px;
        }

        #patient-avatar {
            max-width: 100px;
            border-radius: 50%;
            margin-bottom: 10px;
        }
    </style>
</head>

<body>
    <header>
        <h1>个人中心</h1>
    </header>
    <section>
        <h2>个人信息</h2>
        <p>预约ID：<span id="patient-id-display"></span></p>
        <p >姓名：<span id="name"></span></p>
        <p id="genderAll">性别：<span id="gender"></span></p>
        <p>电话：<span id="phone"></span></p>
        <form>
            <label for="username">用户名：</label>
            <input type="text" id="username" name="username" value="zhangsan" disabled>
            <br>
            <label for="password">密码：</label>
            <input type="password" id="password" name="password" placeholder="********">
            <br>
            <button type="submit">保存更改</button>
        </form>
    </section>
    <section id="billing-section">
        <h2>账单信息</h2>
        <p id="payment-status">未支付</p>
        <p id="payment-amount">支付金额：￥50.00</p>
        <button id="pay-button">立即支付</button>
        <button id="cancel-button">放弃支付</button> <!-- 添加放弃支付按钮 -->
        <p id="countdown"></p>
    </section>
    <section id="medical-record">
        <h2>病历信息</h2>
        <img id="patient-avatar" src="" alt="患者头像">
        <p id="patient-id">患者ID：</p>
        <p id="patient-name">患者名字：</p>
        <p id="patient-birthdate">出生日期：</p>
        <p id="patient-gender">性别：</p>
        <p id="patient-symptoms">症状：</p>
        <p id="admission-date">入院日期：</p>
        <p id="payment-date">付费日期：</p>
    </section>
    <section>
        <!-- 退出登录按钮 -->
        <button id="logoutButton" onclick="logout()">退出登录</button>
    </section>

    <script>
        // 发起 GET 请求
        document.getElementById("patient-id-display").innerText=window.localStorage.getItem("appointmentId")
        let authToken = window.localStorage.getItem('token')
        if (window.localStorage.getItem('patientId') !== '-1') {
            fetch('http://localhost:8888/patient/' + window.localStorage.getItem('patientId'), {
                method: 'GET',
                headers: {
                    'Token': authToken
                }
            }).then(response => {
                // 处理响应状态
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析 JSON 数据
                return response.json();
            })
                .then(data => {
                    document.getElementById("name").innerText = data.name;
                    document.getElementById("gender").innerText = data.gender;
                    document.getElementById("phone").innerText = data.contactNumber;

                    // 处理获取的数据
                    console.log(data);
                })
                .catch(error => {
                    // 处理错误
                    console.error('There has been a problem with your fetch operation:', error);
                });
        }
        else {
            fetch('http://localhost:8888/doctor/' + window.localStorage.getItem('doctorId'), {
                method: 'GET',
                headers: {
                    'Token': authToken
                }
            }).then(response => {
                // 处理响应状态
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析 JSON 数据
                return response.json();
            })
                .then(data => {

                    document.getElementById("name").innerText = data.name;
                    document.getElementById("gender").innerText = data.gender;
                    document.getElementById("phone").innerText = data.contactNumber;

                    // 处理获取的数据
                    console.log(data);
                })
                .catch(error => {
                    // 处理错误
                    console.error('There has been a problem with your fetch operation:', error);
                });
        }
        var myElement = document.getElementById('billing-section');
        // 或者
        // var myElement = document.querySelector('#myElement');
        if(window.localStorage.getItem('patientId')==='-1'){
            // 设置为不显示
            myElement.style.display = 'none';
            document.getElementById("genderAll").style.display='none'
        }


        function formatDate(originalDateString) {
            const originalDate = new Date(originalDateString);

            return originalDate.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
            });
        }
        function logout() {
            console.log(window.localStorage.getItem('token'));
            let authToken = window.localStorage.getItem('token')
            fetch('http://localhost:8888/user/hello', {
                method: 'GET',
                headers: {
                    'Token': authToken
                }
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                window.localStorage.removeItem('token');
                window.location.href = 'login.html';
            })
        }



        document.addEventListener("DOMContentLoaded", function () {
            // 模拟账单未支付状态
            let isPaymentPending = true;
            let countdownInterval;

            // 获取相关元素
            const paymentStatusElement = document.getElementById("payment-status");
            const paymentAmountElement = document.getElementById("payment-amount");
            const payButton = document.getElementById("pay-button");
            const cancelButton = document.getElementById("cancel-button");
            const countdownElement = document.getElementById("countdown");
            const medicalRecordSection = document.getElementById("medical-record");

            // 点击支付按钮时触发事件
            payButton.addEventListener("click", function () {
                if (isPaymentPending) {
                    // 模拟支付请求（可以替换为实际的支付逻辑）
                    simulatePayment();

                    // 更新支付状态
                    isPaymentPending = false;
                    updatePaymentStatus();

                    // 开始倒计时
                    startCountdown(60); // 60秒倒计时，可以根据需要调整

                    // 显示查看病历信息按钮
                    showMedicalRecordButton();
                }
            });

            // 点击放弃支付按钮时触发事件
            cancelButton.addEventListener("click", function () {
                // 取消倒计时
                clearInterval(countdownInterval);
                countdownElement.textContent = "支付已取消";

                // 这里可以添加其他放弃支付的逻辑
                console.log("用户放弃支付");
            });

            // 模拟支付请求的函数
            function simulatePayment() {
                // 这里可以添加实际的支付逻辑
                console.log("模拟支付中...");
                // 模拟支付成功后的异步请求数据库
                setTimeout(function () {
                    // 构建请求URL，携带患者ID参数
                    const patientIdDisplay = document.getElementById("patient-id-display");
                    // 获取患者ID的值
                    const patientId = patientIdDisplay.textContent;
                    const url = `http://localhost:8888/bill/payNow/${patientId}`;

                    fetch(url, {
                        method: 'GET', // 或 'GET'
                        headers: {
                            'Token': window.localStorage.getItem('token'),
                            'Content-Type': 'application/json',
                        },
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log("支付成功后从数据库获取的数据：", data);
                            // 取消倒计时
                            clearInterval(countdownInterval);
                            countdownElement.innerText = "";
                            alert("支付成功")
                        })
                        .catch(error => {
                            console.error("请求数据库出错：", error);
                        });
                }, 1000); // 模拟1秒后模拟支付成功
            }

            // 更新支付状态的函数
            function updatePaymentStatus() {
                paymentStatusElement.textContent = "已支付";
            }

            // 开始倒计时的函数
            function startCountdown(seconds) {
                let remainingTime = seconds;
                countdownElement.textContent = `剩余时间: ${remainingTime}秒`;

                countdownInterval = setInterval(function () {
                    remainingTime--;

                    if (remainingTime <= 0) {
                        clearInterval(countdownInterval);
                        countdownElement.textContent = "支付超时";
                        // 可以在这里添加超时后的处理逻辑
                    } else {
                        countdownElement.textContent = `剩余时间: ${remainingTime}秒`;
                    }
                }, 1000);
            }

            // 显示查看病历信息按钮和病历信息的函数
            function showMedicalRecordButton() {
                const viewMedicalRecordButton = document.createElement("button");
                viewMedicalRecordButton.textContent = "查看病历信息";
                viewMedicalRecordButton.addEventListener("click", function () {
                    // 检查支付状态，只有支付成功才显示病历信息
                    if (!isPaymentPending) {
                        // 模拟异步请求获取病历信息
                        simulateMedicalRecordRequest();
                    }
                });

                document.getElementById("billing-section").appendChild(viewMedicalRecordButton);
            }

            // 模拟异步请求获取病历信息的函数
            function simulateMedicalRecordRequest() {
                // 模拟异步请求
                setTimeout(function () {
                    // 构建请求URL，携带患者ID参数

                    // 获取患者ID的值
                    const patientId = window.localStorage.getItem("patientId")

                    // 构建请求URL
                    const apiUrl = `http://localhost:8888/records/${patientId}`;

                    // 使用 Fetch API 发送GET请求
                    fetch(apiUrl, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Token': window.localStorage.getItem('token'),
                            // 可以添加其他必要的头部信息
                        },
                    }).then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    }).then(data => {
                            console.log(data);
                            updateMedicalRecord(data);
                        }).catch(error => {
                            // 在这里处理请求失败的情况
                            console.error("请求病历信息出错：", error);
                        });
                }, 1000); // 模拟1秒后获取到病历信息
            }

            // 更新病历信息的函数
            function updateMedicalRecord(data) {
                const patientAvatar = document.getElementById("patient-avatar");
                const patientIdDisplay = document.getElementById("patient-id-display"); // 新添加的元素
                const patientName = document.getElementById("patient-name");
                const patientBirthdate = document.getElementById("patient-birthdate");
                const patientGender = document.getElementById("patient-gender");
                const patientSymptoms = document.getElementById("patient-symptoms");
                const admissionDate = document.getElementById("admission-date");
                const paymentDate = document.getElementById("payment-date");

                // 更新病历信息的显示
                patientAvatar.src = data.avatar;
                patientIdDisplay.textContent = data.patientId; // 更新患者ID显示
                patientName.textContent = `患者名字：${data.patientName}`;
                patientBirthdate.textContent = `出生日期：${formatDate(data.dateOfBirth)}`;
                patientGender.textContent = `性别：${data.gender}`;
                patientSymptoms.textContent = `症状：${data.diagnosisName}`;
                admissionDate.textContent = `入院日期：${formatDate(data.admissionDate)}`;
                paymentDate.textContent = `付费日期：${formatDate(data.dischargeDate)}`;

                // 显示病历信息部分
                medicalRecordSection.style.display = "block";
            }
        });
    </script>
</body>

</html>